﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Logging
{
    public class FileLogger : LogService
    {
        private const int MAX_MESSAGES = 15;
        private StringBuilder _messageBuffer;
        private string _filePath;
        private int _messages;

        public FileLogger(string folderPath)
        {
            _messages = 0;
            _messageBuffer = new StringBuilder();
            _filePath = Path.Combine(folderPath, String.Format("{0}.{1}", DateTime.Now.ToString().Replace('/','_').Replace(':','_'), "txt"));
        }

        protected override void OnDispose(bool disposing)
        {
            if (disposing)
                ForceFlush();
        }

        protected override void writeFormattedErrorMessage(string message, params object[] args)
        {
            _messageBuffer.AppendFormat(message + Environment.NewLine + Environment.NewLine, args);
            checkFlush();
        }

        protected override void writeFormattedWarningMessage(string message, params object[] args)
        {
            _messageBuffer.AppendFormat(message + Environment.NewLine + Environment.NewLine, args);
            checkFlush();
        }

        protected override void writeFormattedMessage(string message, params object[] args)
        {
            _messageBuffer.AppendFormat(message + Environment.NewLine + Environment.NewLine, args);
            checkFlush();
        }

        public override void ForceFlush()
        {
            _messages = MAX_MESSAGES;
            checkFlush();
        }

        private void checkFlush()
        {
            _messages++;

            if (_messages >= MAX_MESSAGES)
            {
                using (StreamWriter stream = fopen(_filePath))
                {
                    stream.Write(_messageBuffer.ToString());
                    stream.Flush();
                }

                _messages = 0;
                _messageBuffer.Clear();
            }
        }

        private StreamWriter fopen(string filePath)
        {
            StreamWriter stream = null;

            string directoryName = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(directoryName))
                Directory.CreateDirectory(directoryName);

            if (File.Exists(filePath))
                stream = File.CreateText(filePath);
            else
                stream = File.AppendText(filePath);

            return stream;
        }
    }
}
